<?php

namespace SunAdmin\Service;


class ConsoleInfoPrinter
{
    private array $titleLines = [];
    private array $infoRows = [];
    private int $width;

    public function __construct(int $width = 60)
    {
        $this->width = $width;
    }

    public function setTitle(string|array $lines): void
    {
        $this->titleLines = is_array($lines) ? $lines : [$lines];
    }

    public function addInfo(string $key, string $value): void
    {
        $this->infoRows[] = [$key, $value];
    }

    private function printLine(): void
    {
        echo '+' . str_repeat('-', $this->width - 2) . '+' . PHP_EOL;
    }

    private function printCenter(string $text): void
    {
        $padded = $this->mbPad($text, $this->width - 2, STR_PAD_BOTH);
        echo '|' . $padded . '|' . PHP_EOL;
    }

    private function printKeyValue(string $key, string $value): void
    {
        $usableWidth = $this->width - 4; // 去掉边框和空格
        $leftPadding = 10;
        $rightPadding = 10;
        $contentWidth = $usableWidth - $leftPadding - $rightPadding;

        $keyWidth = intval($contentWidth * 0.55);
        $valueWidth = $contentWidth - $keyWidth;

        $keyStr = $this->mbPad($key, $keyWidth, STR_PAD_RIGHT);
        $valStr = $this->mbPad($value, $valueWidth, STR_PAD_LEFT);

        echo '| ' . str_repeat(' ', $leftPadding) . $keyStr . $valStr . str_repeat(' ', $rightPadding) . ' |' . PHP_EOL;
    }

    private function mbPad(string $text, int $width, int $padType = STR_PAD_RIGHT): string
    {
        $textWidth = mb_strwidth($text, 'UTF-8');
        $padLength = $width - $textWidth;

        if ($padLength <= 0) return $text;

        return match ($padType) {
            STR_PAD_LEFT => str_repeat(' ', $padLength) . $text,
            STR_PAD_BOTH => str_repeat(' ', floor($padLength / 2)) . $text . str_repeat(' ', ceil($padLength / 2)),
            default => $text . str_repeat(' ', $padLength),
        };
    }

    public function render(): void
    {
        $this->printLine();

        foreach ($this->titleLines as $title) {
            $this->printCenter($title);
        }

        $this->printLine();

        foreach ($this->infoRows as [$key, $val]) {
            $this->printKeyValue($key, $val);
        }

        $this->printLine();
    }
}